<?php
class IndexService{

	public  $dbutil;
	function __construct($dbutil){
		$this->dbutil =  $dbutil;
	}

    /**
     * 查询文章的列表封装方法
     * @param $begin           查询开始的位置
     * @param $end             查询结束位置
     * @param string $orderBy  排序条件，默认是按时间
     * @param string $where    where条件，有默认值
     * @return array           最新添加了tag的列表
     */
    public function loadPosts4ListCategory($begin, $end,$orderBy="order by  post_date desc ",$where='', $load=''){
        //load posts
        $limit =" limit $begin,$end ";
        $db_filed = "ID, post_title, post_author, comment_count, post_excerpt, post_date, post_file_location, post_status, posts.post_category, category_name, click_count ";
        $where_mustHave = " post_status = 0 AND posts.post_category=category_id ";
        $db_where = empty($where)?$where_mustHave:$where.$where_mustHave;
        $queryPostSql = 'SELECT '.$db_filed.' FROM posts, post_category WHERE '.$db_where.$orderBy.$limit;

        $postLists = $this->dbutil->get_results($queryPostSql);

        //fill sort data
        $postIDs =array();
        if(empty($postLists)){
            return 'empty';
        }else{
            foreach ($postLists as $k => $post) {
                $post->sort_date = $begin + $k + 1;//实时 排序字段
                $post->sort_popularity = $post->click_count;//实时 排序字段
                $postIDs[] = $post->ID;
            }
        }

        //fill tag
        $tags = $this->findTagsByPostIds($postIDs);
        $this->fillTag4PostList($postLists,$tags);
        //fill href
        $this->fillPostHref($postLists);
        $this->fillPostAuth($postLists);
        $result;
        if(!empty($load)){
         	$result = $postLists;
        }else {
        	$result = $this->createHtml($postLists);
        }
        
        return $result;
    }
    
    /**
     * 
     * 生成页面数据
     * @param unknown_type $postLists
     */
    public function createHtml($postLists){
    	$posts_html = '';
		foreach ($postLists as $k => $val) {
			$tags = $val->tag_id;
			$taghtml = '';
			if(!empty($tags)){
				$tagsArr = explode(",", $val->tag_name);
                $tagids =  explode(",", $val->tag_id);
				foreach ($tagsArr as $key => $value) {
					$taghtml .= "<a href=\"".WEBSITE_URL."tag/showtag/$tagids[$key]\">".$value."</a>";
				}
			}else {
				$taghtml = '';
			}
				
			$posts_html .= "<li data-date=".$val->sort_date." data-popularity=".$val->sort_popularity." >" .
			"<a href=\"".$val->href."\"><img src=\"".$val->post_file_location."\" class=\"f_l\" onerror=\"this.src='".WEBSITE_URL."public/images/error.png';\"/></a>".
			"<div class=\"f_l\">".
			"<a href=\"".$val->href."\">".
			"<h4>".$val->post_title."</h4>".
			"<span><font>".$val->post_author."</font>发表于<time>".$val->post_date."</time></span>".
			"<p>".$val->post_excerpt."</p>".
			"</a>".
			"<div class=\"texttag\">".$taghtml."</div>".
			"</div>".
			"</li>";	
		}
		return $posts_html;
    }
    
   public function findTagsByPostIds($postIds){
       if(empty($postIds)){
           return '';
       }
       $postIdsStr = implode(",", $postIds);
       $tagSql = "SELECT post_id, t.tag_id, tag_name  FROM tags t , post_tag pt WHERE t.tag_id = pt.tag_id and pt.post_id IN(".$postIdsStr.")";
       $tags = $this->dbutil->get_results($tagSql);
       return $tags;
  }


    private function fillTag4PostList($posts,$tags){
        foreach ($posts as $k => $post) {
            $id = $post->ID;
            $tag_id = '';
            $tag_name = '';
            foreach ($tags as $t => $tag) {
                $post_id = $tag->post_id;
                if($id==$post_id){
                    $tag_id .= $tag->tag_id . ',';
                    $tag_name .= $tag->tag_name . ',';

                }
            }
            $post->tag_id = $tag_id;
            $post->tag_name = $tag_name;
        }
        return $posts;
    }

    /**
     * 填充文章的连接地址
     * @param $posts
     * @return mixed
     */
    public function fillPostHref($posts){
        foreach ($posts as $k => $post) {
            if(empty($post)){
                continue;
            }
            $cid = $post->post_category;
            require_once SERVICE . DS . 'CategoryService.class.php';
            $categoryService = new CategoryService( $this->dbutil );
            $pcategory = $categoryService->getPCategory($cid);
            if($cid ==$pcategory->category_id){
                $post->href=$cid."/".$post->ID.".html";
            }else{
                $post->href=$pcategory->category_id."/".$cid."/".$post->ID.".html";
            }

        }
        return $posts;
    }
    /**
     * 填充文章的作者信息,这里将来都有可能扩展
     * 比如，扩展成点击作者，连接到作者页面
     * @param $posts
     * @return mixed
     */
    private function fillPostAuth($posts){
        require_once SERVICE . DS . 'admin' . DS . 'AdminuserService.class.php';
        foreach ($posts as $k => $post) {
            $userid = $post->post_author;
                $userService = new AdminuserService ($this->dbutil );
                $user = $userService->getAdminByID($userid);
                $post->post_author = $user->user_name;
        }
        return $posts;
    }


    /**
	 *
	 * 首页加载文章
	 */
	public function loadPosts($page, $rows, $click_count){
		$limit =" limit $page,$rows ";
		$order = empty($click_count)?"":$click_count.' desc, ';
		$sql = 'SELECT ID, post_title, post_author, comment_count, post_excerpt, post_date, post_file_location, post_status, posts.post_category, category_name, click_count FROM posts, post_category WHERE posts.post_category=category_id AND post_status = 0 order by '.$order.' post_date desc '.$limit;

		$result = $this->dbutil->get_results($sql);

		$postID;
		if(!empty($result)){
			$count = count($result);
			foreach ($result as $k => $val) {
				$val->sort_date = $page + $k + 1;//实时 排序字段
				$val->sort_popularity = $val->click_count;//实时 排序字段
				$postID .= $val->ID . ',';
			}
		}else{
			return 'empty';
		}

		$targsSql = "SELECT post_id, t.tag_id, tag_name  FROM tags t , post_tag pt WHERE t.tag_id = pt.tag_id and pt.post_id IN(".substr($postID, 0, strlen($postID)-1).")";
		$targs = $this->dbutil->get_results($targsSql);
		
		$postid;
		foreach ($result as $k => $val) {
			$id = $val->ID;
			$tag_id = '';
			$tag_name = '';
			foreach ($targs as $t => $value) {
				$post_id = $value->post_id;
				if($id==$post_id){
					$tag_id .= $value->tag_id . ',';
					$tag_name .= $value->tag_name . ',';
				}
			}
			$val->tag_id = $tag_id;
			$val->tag_name = $tag_name;
		}
		return $result;
	}
	

	
	public function saveConnects($sql){
		return $this->dbutil->query($sql);
	}
}